package org.dromara.web.service.business;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.checkerframework.checker.units.qual.A;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.dao.business.domain.*;
import org.dromara.dao.business.mapper.*;
import org.dromara.web.controller.app.req.SmartAgentCreateReq;
import org.dromara.web.controller.app.req.SmartAgentUpdateReq;
import org.dromara.web.domain.app.SmartAgentDetailVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class SmartAgentService {

    @Autowired
    SmartAgentMapper smartAgentMapper;
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    SmartAgentCategoryMapper smartAgentCategoryMapper;
    @Autowired
    SmartAgentSettingService smartAgentSettingService;
    @Autowired
    SmartAgentSettingMapper smartAgentSettingMapper;
    @Autowired
    SmartAgentI18nMapper smartAgentI18nMapper;


    public TableDataInfo<SmartAgent> queryPageList(SmartAgentQuery query, PageQuery pageQuery) {
        return new TableDataInfo(
                smartAgentMapper.paginationSelectList(query, pageQuery),
                smartAgentMapper.paginationSelectCount(query)
        );
    }


    public SmartAgent queryById(Long id) {
        return smartAgentMapper.selectById(id);
    }


    @Transactional
    public SmartAgent insert(SmartAgent entity) {
        if (entity.getModelId() != null) {
            Model model = modelMapper.selectById(entity.getModelId());
            if (model != null) {
                entity.setModelIcon(model.getIcon());
                entity.setModelName(model.getName());
                entity.setModelValue(model.getValue());
            }
        }
        if (entity.getCategoryId() != null) {
            SmartAgentCategory category = smartAgentCategoryMapper.selectById(entity.getCategoryId());
            if (category != null) {
                entity.setCategoryName(category.getName());
            }
        }
        smartAgentMapper.insert(entity);
        return entity;
    }

    @Transactional
    public void updateById(SmartAgent update) {

        SmartAgent entity = smartAgentMapper.selectById(update.getId());
        if (entity == null) {
            throw new ServiceException();
        }
        entity.setName(update.getName());
        entity.setDescription(update.getDescription());
        entity.setPrompt(update.getPrompt());
        entity.setUserId(update.getUserId());
        entity.setModelId(update.getModelId());
        if (update.getModelId() != null) {
            Model model = modelMapper.selectById(update.getModelId());
            if (model != null) {
                entity.setModelIcon(model.getIcon());
                entity.setModelName(model.getName());
                entity.setModelValue(model.getValue());
            }
        }
        entity.setCategoryId(update.getCategoryId());
        if (update.getCategoryId() != null) {
            SmartAgentCategory category = smartAgentCategoryMapper.selectById(update.getCategoryId());
            if (category != null) {
                entity.setCategoryName(category.getName());
            }
        }
        entity.setStatus(update.getStatus());
        entity.setHot(update.getHot());
        entity.setIcon(update.getIcon());
        entity.setUpdateTime(LocalDateTime.now());
        smartAgentMapper.updateById(entity);
    }


    @Transactional
    public void deleteById(Long id) {
        smartAgentMapper.deleteById(id);
    }

    @Transactional
    public void deleteByIds(Long[] ids) {
        smartAgentMapper.deleteByIds(Arrays.asList(ids));
    }




    public List<SmartAgent> getSmartAgent(Long categoryId, String search, String lang, Long userId) {

//        LambdaQueryWrapper<SmartAgent> queryWrapper = new LambdaQueryWrapper<SmartAgent>();
//        if (categoryId != null) {
//            queryWrapper.eq(SmartAgent::getCategoryId, categoryId);
//        }
//        if (StringUtils.isNotEmpty(search)) {
//            queryWrapper.like(SmartAgent::getName, search);
//        }
//        queryWrapper.eq(SmartAgent::getStatus, true);
//        return smartAgentMapper.selectList(queryWrapper);
        return smartAgentMapper.searchAgent(categoryId, search, lang, userId);
    }


    public SmartAgentDetailVO detail(Long agentId, String lang) {
        SmartAgentDetailVO detailVO = new SmartAgentDetailVO();
        SmartAgent smartAgent = smartAgentMapper.selectById(agentId);
        if (smartAgent != null) {
            BeanUtils.copyProperties(smartAgent, detailVO);
        }
        if (StringUtils.isNotEmpty(lang)) {
            SmartAgentI18n smartAgentI18n = smartAgentI18nMapper.selectOne(
                new LambdaQueryWrapper<SmartAgentI18n>().eq(SmartAgentI18n::getAgentId, agentId)
                    .eq(SmartAgentI18n::getLang, lang)
            );
            if (smartAgentI18n != null) {
                detailVO.setName(smartAgentI18n.getName());
                detailVO.setDescription(smartAgentI18n.getDescription());
                detailVO.setPrompt(smartAgentI18n.getPrompt());
            }
        }

        detailVO.setSetting(smartAgentSettingService.findSetting(agentId, LoginHelper.getAppUserId()));

        return detailVO;
    }



    public SmartAgent agentDetail(Long agentId, String lang) {
        SmartAgent smartAgent = smartAgentMapper.selectById(agentId);

        if (StringUtils.isNotEmpty(lang)) {
            SmartAgentI18n smartAgentI18n = smartAgentI18nMapper.selectOne(
                new LambdaQueryWrapper<SmartAgentI18n>().eq(SmartAgentI18n::getAgentId, agentId)
                    .eq(SmartAgentI18n::getLang, lang)
            );
            if (smartAgentI18n != null) {
                smartAgent.setName(smartAgentI18n.getName());
                smartAgent.setDescription(smartAgentI18n.getDescription());
                smartAgent.setPrompt(smartAgentI18n.getPrompt());
            }
        }

        return smartAgent;
    }


    @Transactional
    public void createAgent(SmartAgentCreateReq req) {
        SmartAgent smartAgent = new SmartAgent();
        LoginUser loginUser = LoginHelper.getAppLoginUser();
        smartAgent.setUserId(loginUser.getUserId());
        smartAgent.setName(req.getName());
        smartAgent.setPrompt(req.getPrompt());
        smartAgent.setDescription(req.getDescription());
        smartAgent.setIcon(req.getIcon());
        smartAgent.setModelId(req.getModelId());
        if (req.getModelId() != null) {
            Model model = modelMapper.selectById(req.getModelId());
            if (model != null) {
                smartAgent.setModelIcon(model.getIcon());
                smartAgent.setModelName(model.getName());
                smartAgent.setModelValue(model.getValue());
            }
        }
        smartAgentMapper.insert(smartAgent);

        SmartAgentSetting smartAgentSetting = new SmartAgentSetting();
        smartAgentSetting.setUserId(loginUser.getUserId());
        smartAgentSetting.setAgentId(smartAgent.getId());
        smartAgentSetting.setDataSwitch(req.getData());
        smartAgentSetting.setNetworkSwitch(req.getNetwork());
        smartAgentSetting.setImageSwitch(req.getImage());

        smartAgentSettingMapper.insert(smartAgentSetting);
    }


    @Transactional
    public void updateAgent(SmartAgentUpdateReq req) {
        SmartAgent smartAgent = smartAgentMapper.selectById(req.getAgentId());

        smartAgent.setName(req.getName());
        smartAgent.setPrompt(req.getPrompt());
        smartAgent.setIcon(req.getIcon());
        smartAgent.setModelId(req.getModelId());
        smartAgent.setDescription(req.getDescription());
        if (req.getModelId() != null) {
            Model model = modelMapper.selectById(req.getModelId());
            if (model != null) {
                smartAgent.setModelIcon(model.getIcon());
                smartAgent.setModelName(model.getName());
                smartAgent.setModelValue(model.getValue());
            }
        }
        smartAgentMapper.updateById(smartAgent);

        SmartAgentSetting smartAgentSetting = smartAgentSettingService.findSetting(req.getAgentId(), LoginHelper.getAppUserId());

        smartAgentSetting.setAgentId(smartAgent.getId());
        smartAgentSetting.setDataSwitch(req.getData());
        smartAgentSetting.setNetworkSwitch(req.getNetwork());
        smartAgentSetting.setImageSwitch(req.getImage());

        smartAgentSettingMapper.updateById(smartAgentSetting);
    }


    public List<SmartAgent> queryHotAgent(Long userId, String lang) {
        List<SmartAgent> agents = smartAgentMapper.queryHotAgent(userId);
        if (CollectionUtils.isNotEmpty(agents)) {
            Map<Long, SmartAgent> agentMap = new HashMap<>();
            for (SmartAgent agent : agents) {
                agentMap.put(agent.getId(), agent);
            }
            List<Long> ids = new ArrayList<>();
            ids.addAll(agentMap.keySet());
            List<SmartAgentI18n> i18nList = smartAgentI18nMapper.selectList(new LambdaQueryWrapper<SmartAgentI18n>().in(SmartAgentI18n::getAgentId, ids).eq(SmartAgentI18n::getLang, lang));
            if (CollectionUtils.isNotEmpty(i18nList)) {
                for (SmartAgentI18n i18n : i18nList) {
                    SmartAgent agent = agentMap.get(i18n.getAgentId());
                    if (agent != null) {
                        agent.setName(i18n.getName());
                        agent.setPrompt(i18n.getPrompt());
                        agent.setDescription(i18n.getDescription());
                    }
                }
            }
        }
        return agents;
    }


    public List<SmartAgent> queryUserAgentList(Long userId) {
        return smartAgentMapper.queryUserAgentList(userId);
    }


    @Transactional
    public void deleteAgent(Long agentId, Long userId) {
        SmartAgent smartAgent = smartAgentMapper.selectById(agentId);
        if (smartAgent == null || !smartAgent.getUserId().equals(userId) ) {
            throw new ServiceException("当前智能体不能删除");
        }

        smartAgentMapper.deleteById(agentId);
    }

    @Transactional
    public void updateModel(Long agentId, Long modelId) {
        SmartAgent smartAgent = smartAgentMapper.selectById(agentId);
        Model model = modelMapper.selectById(modelId);
        smartAgent.setModelId(modelId);
        smartAgent.setModelIcon(model.getIcon());
        smartAgent.setModelName(model.getName());
        smartAgent.setModelValue(model.getValue());
        smartAgentMapper.updateById(smartAgent);
    }


    public List<SmartAgentI18n> listI18n(Long categoryId) {
        return smartAgentI18nMapper.selectList(new LambdaQueryWrapper<SmartAgentI18n>().eq(SmartAgentI18n::getAgentId, categoryId));
    }

    public void addI18n(SmartAgentI18n entity) {
        smartAgentI18nMapper.insert(entity);
    }

    public void updateI18n(SmartAgentI18n update) {
        SmartAgentI18n i18n = smartAgentI18nMapper.selectById(update.getId());
        i18n.setName(update.getName());
        i18n.setLang(update.getLang());
        i18n.setPrompt(update.getPrompt());
        i18n.setDescription(update.getDescription());
        i18n.setAgentId(update.getAgentId());
        smartAgentI18nMapper.updateById(i18n);
    }

    public void deteteI18n(Long id) {
        smartAgentI18nMapper.deleteById(id);
    }

}
